package com.pt25.base.dep.log;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Logback 日志工具类
 * 支持不同环境的日志配置和结构化日志
 */
@Component
public class LogUtil {

    private static final String TRACE_ID = "traceId";
    private static final String USER_ID = "userId";
    private static final String MODULE = "module";

    @Value("${spring.profiles.active:default}")
    private String activeProfile;

    /**
     * 获取Logger实例
     */
    public static Logger getLogger(Class<?> clazz) {
        return LoggerFactory.getLogger(clazz);
    }

    /**
     * 设置跟踪ID
     */
    public static void setTraceId(String traceId) {
        if (traceId == null || traceId.trim().isEmpty()) {
            traceId = generateTraceId();
        }
        MDC.put(TRACE_ID, traceId);
    }

    /**
     * 设置用户ID
     */
    public static void setUserId(String userId) {
        MDC.put(USER_ID, userId);
    }

    /**
     * 设置模块名
     */
    public static void setModule(String module) {
        MDC.put(MODULE, module);
    }

    /**
     * 清除MDC
     */
    public static void clearMdc() {
        MDC.clear();
    }

    /**
     * 生成跟踪ID
     */
    public static String generateTraceId() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }

    /**
     * 获取当前跟踪ID
     */
    public static String getCurrentTraceId() {
        return MDC.get(TRACE_ID);
    }

    /**
     * 业务日志 - 记录关键业务操作
     */
    public static void bizLog(Logger logger, String action, Object data, String message) {
        Map<String, Object> logData = new HashMap<>();
        logData.put("action", action);
        logData.put("data", data);
        logData.put("message", message);
        logData.put("type", "BIZ");

        logger.info("BIZ_LOG - {} - {}", action, toJsonString(logData));
    }

    /**
     * 性能日志 - 记录方法执行时间
     */
    public static void perfLog(Logger logger, String methodName, long startTime, long endTime) {
        long cost = endTime - startTime;
        Map<String, Object> logData = new HashMap<>();
        logData.put("method", methodName);
        logData.put("startTime", startTime);
        logData.put("endTime", endTime);
        logData.put("cost", cost);
        logData.put("type", "PERF");

        if (cost > 1000) { // 超过1秒记录为WARN
            logger.warn("PERF_LOG - {} - {} - cost: {}ms", methodName, toJsonString(logData), cost);
        } else {
            logger.info("PERF_LOG - {} - {} - cost: {}ms", methodName, toJsonString(logData), cost);
        }
    }

    /**
     * 错误日志 - 结构化错误信息
     */
    public static void errorLog(Logger logger, String message, Throwable throwable, Object context) {
        Map<String, Object> logData = new HashMap<>();
        logData.put("message", message);
        logData.put("context", context);
        logData.put("exception", throwable != null ? throwable.getMessage() : null);
        logData.put("type", "ERROR");

        if (throwable != null) {
            logger.error("ERROR_LOG - {} - context: {}", message, toJsonString(logData), throwable);
        } else {
            logger.error("ERROR_LOG - {} - context: {}", message, toJsonString(logData));
        }
    }

    /**
     * 调试日志 - 只在开发/测试环境输出
     */
    public static void debugLog(Logger logger, String message, Object data) {
        if (logger.isDebugEnabled()) {
            Map<String, Object> logData = new HashMap<>();
            logData.put("message", message);
            logData.put("data", data);
            logData.put("type", "DEBUG");

            logger.debug("DEBUG_LOG - {} - data: {}", message, toJsonString(logData));
        }
    }

    /**
     * SQL日志 - 记录SQL执行信息
     */
    public static void sqlLog(Logger logger, String sql, Object params, long cost) {
        Map<String, Object> logData = new HashMap<>();
        logData.put("sql", sql);
        logData.put("params", params);
        logData.put("cost", cost);
        logData.put("type", "SQL");

        if (cost > 1000) {
            logger.warn("SQL_LOG - cost: {}ms, sql: {}, params: {}", cost, sql, toJsonString(params));
        } else {
            logger.info("SQL_LOG - cost: {}ms, sql: {}, params: {}", cost, sql, toJsonString(params));
        }
    }

    /**
     * 审计日志 - 记录重要操作审计
     */
    public static void auditLog(Logger logger, String operation, String operator, Object before, Object after) {
        Map<String, Object> logData = new HashMap<>();
        logData.put("operation", operation);
        logData.put("operator", operator);
        logData.put("before", before);
        logData.put("after", after);
        logData.put("timestamp", System.currentTimeMillis());
        logData.put("type", "AUDIT");

        logger.info("AUDIT_LOG - {} by {} - {}", operation, operator, toJsonString(logData));
    }

    /**
     * 对象转JSON字符串
     */
    private static String toJsonString(Object obj) {
        if (obj == null) {
            return "null";
        }
        try {
            // 可以使用 Jackson 或其他 JSON 库
            // 这里简单实现，实际项目中建议使用 JSON 库
            if (obj instanceof String) {
                return (String) obj;
            }
            return obj.toString();
        } catch (Exception e) {
            return obj.toString();
        }
    }

    /**
     * 判断当前环境
     */
    public boolean isProd() {
        return "prod".equals(activeProfile);
    }

    public boolean isTest() {
        return "test".equals(activeProfile);
    }

    public boolean isDev() {
        return "dev".equals(activeProfile);
    }
}